from math import log
import pyautogui
import pyperclip
import time
import psutil
import win32gui
import win32con
import pygetwindow
import win32api
import win32process
import lxlog
import datetime
import os
import LXWindowUtil
from LXWindowUtil import change_window,check_search_result,click_window,double_click_window,get_window_active,clear_search_box,paste_message,get_clipboard_text,screenshot,locate_on_screen,click_window_by_image,click,url_image_to_clipboard,find_window_handle


# 查找并激活企业微信窗口
def active_wxwork_window():
    window, hwnd = get_window_active(window_name="企业微信",exe_name="wxwork.exe", max_retries=5)
    if window is None:
        lxlog.error("未找到企业微信窗口,无法发送消息。")
        return None
    change_window(window,hwnd,800,600,x=0,y=140) # 调整企业微信窗口大小
    return window

# 搜索框是否未打开
def active_wxwork_search_window():
    lxlog.info("激活搜索框")
    full_search_window, hwnd = get_window_active(window_name='全局搜索',exe_name="wxwork.exe", max_retries=1)
    if full_search_window is None:
        lxlog.info("未找到全局搜索窗口。")
        window = active_wxwork_window()
        lxlog.info("打开搜索框")
        click_window(window,170,40)
        click_window(window,170,82)
        full_search_window, hwnd = get_window_active(window_name='全局搜索',exe_name="wxwork.exe", max_retries=3)
        change_window(full_search_window,hwnd,800,600,x=320,y=70) # 调整搜索框大小
        click_window(full_search_window,140,96) # 点击群聊
        click_window(full_search_window,750,300)
        #click_window(full_search_window,700,385)
    return full_search_window,hwnd
#active_wxwork_search_window()
def searchGroup(group_name):
    lxlog.info(f"搜索群聊:{group_name}")
    x,y = locate_on_screen(r'wxqjss.png',region=(320,70, 66, 80))
    if x is None or y is None:
        lxlog.error(f"未找到全局搜索框!")
        return False
        #full_search_window,hwnd = active_wxwork_search_window()# 激活搜索框
        #if full_search_window is None:
        #    return False
    click(450,120) # 点击搜索框
    clear_search_box() # 清空搜索框
    paste_message(group_name) # 发送搜索内容
    # 获取微信成员所在图标位置
    if not check_search_result(350, 180,100,60):
        lxlog.error("未查询到群名:"+group_name)
        return False
    # 进入群聊
    lxlog.debug("进入群聊..."+group_name)
    pyautogui.press('enter')
    time.sleep(1)  # 等待群聊窗口加载
    lxlog.debug("打开聊天框")
    x,y = locate_on_screen(r'wxwaibu.png',region=(60,200, 250, 60))
    if x is None or y is None:
        lxlog.error(f"未找到外部群!")
        return False
    click(200,245,clicks=2) # 双击打开第一个聊天
    time.sleep(1)
    return True

# 激活群聊窗口
def active_group_chat_window(group_name):
    lxlog.debug(f"激活群聊窗口...{group_name}")
    group_window, hwnd = get_window_active(window_name=group_name,exe_name="wxwork.exe")
    if group_window is None:
        lxlog.debug("未找到聊天窗口!进行搜索")
        if not searchGroup(group_name):
            return None,None
        group_window, hwnd = get_window_active(window_name=group_name,exe_name="wxwork.exe", max_retries=3)
        if group_window is None:
            lxlog.debug("未找到聊天窗口!")
            click(1340,253) # 点击关闭框
            return None,None
        change_window(group_window,hwnd,800,560) # 调整企业微信聊天窗口大小
    return group_window,hwnd
# 进入群聊
def enter_group_chat(group_name):
    lxlog.debug(f"进入群聊...{group_name}")
    group_window, hwnd = active_group_chat_window(group_name)
    if group_window is None:
        return None
    lxlog.info(f"进入群聊...{group_name}")
    time.sleep(1)
    click_window(group_window,300,470) # 点击文字框
    return group_window # 进入群聊

def sendMsg(group_name,msgs,at=None):
    lxlog.info(f"发送消息:{group_name} {msgs} {at}")
    try:
        group_window = enter_group_chat(group_name)
        if group_window is not None:
            lxlog.info("已成功进入群聊，准备发送消息。")
            clear_search_box()
            
            if at:
                lxlog.info(f"准备发送 @{at} 的消息...")
                paste_message(f"@{at}")
                pyautogui.press('enter')
                time.sleep(1)
            # 根据参数决定发送文本还是图片
            for msg in msgs:
                type = msg.get("type")
                content = msg.get("content")
                if type == 'txt':
                    # 输入消息内容
                    lxlog.info(f"正在输入消息内容:{content}")
                    paste_message(content)
                    pyautogui.press('enter')
                    lxlog.info("消息已发送。")
                elif type == 'img':
                    lxlog.info(f"准备发送图片...:{content}")
                    url_image_to_clipboard(content)
                    pyautogui.press('enter')
                    lxlog.info("图片已发送。")
                time.sleep(1)
            click_window(group_window,780,14) # 点击关闭框
        else:
            lxlog.error(f"未能确认找到指定的群聊![{group_name}]")
    except Exception as e:
        lxlog.error(f"发送消息失败: {str(e)}")


# 踢出群聊
def kickout_group(group_name, users):
    lxlog.info(f"踢出群聊:{group_name} {users}")
    duser = []
    group_window, hwnd = active_group_chat_window(group_name)
    if group_window is None:
        return duser
    for user_name in users:
        click_window(group_window,300,470) # 点击文字框
        click_window(group_window,783,100) # 点击右上角三个点
        click_window(group_window,810,120) # 搜索群成员
        paste_message(user_name) # 发送搜索内容
        # 获取微信成员所在图标位置
        x,y = locate_on_screen(r'wxtxt.png',region=(group_window.left+630, group_window.top+90, 100, 500))
        if x is None or y is None:
            lxlog.error(f"未找到微信成员:"+user_name)
            continue
        region = (x, y, 130, 200) # 右键后显示的数据
        # 计算成员所在位置 微信下面第一个人
        x1 = x+20
        y1 = y+30
        click(x1,y1, button='right') # 右键点击成员
        if click_window_by_image(r'wxfzzh.png',region=region): # 点击复制账号
            copy_name = get_clipboard_text()
            if copy_name == user_name+';':
                click(x1,y1, button='right') # 右键点击成员
                if click_window_by_image(r'wxycql.png',region=region): # 点击移出群聊
                    click_window(group_window,410,330) # 点击确定
                    lxlog.info("已成功踢出群聊:"+user_name)
                    duser.append(user_name)
            else :
                lxlog.error(f"未查询到昵称一致的用户[{user_name}]:[{copy_name}]")
    click_window(group_window,780,14) # 点击关闭框
    return duser
